package com.every.scheduler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.every.entity.EmailUser;
import com.every.service.EmailRecordService;
import com.every.service.EmailUserService;
import com.every.utils.FtlUtil;
import com.every.utils.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: yh
 * @date: 2022/11/1
 */
@Slf4j
@Component
public class EmailTask {
    @Autowired(required = false)
    private JavaMailSender mailSender;
    @Resource
    private EmailRecordService emailRecordService;
    @Resource
    private EmailUserService emailUserService;

    /**
     * 本身邮件的发送者，来自邮件配置
     *
     * @author yh
     * @date 2022/6/4
     */
    @Value("${spring.mail.username}")
    private String userName;
    /**
     * 发送者昵称
     *
     * @author: yh
     * @date: 2022/6/4
     */
    @Value("${spring.mail.nickname}")
    private String nickname;
    // 邮件主题
    @Value("${spring.mail.subject}")
    private String subject;

    @Value("${secret.coder.access-key}")
    private String CODER_ACCESS_KEY;
    @Value("${secret.coder.secret-key}")
    private String CODER_SECRET_KEY;

    //默认编码
    public static final String DEFAULT_ENCODING = "UTF-8";

    public Map<String, String> getContent() {
        Map<String, String> resultMap = new HashMap<>(10);
        // 每日一图
        JSONObject imageResultObject = RequestUtil.postForObject(RequestUtil.TODAY_IMAGE_URL, null);
        if (imageResultObject != null && "200".equals(imageResultObject.getString("code"))) {
            JSONObject imgObject = imageResultObject.getJSONObject("data");
//            String imageTitle = imgObject.getString("title");
            String imageUrl = imgObject.getString("url");
            // 版权
//            String imageCopyright = imgObject.getString("copyright");
//            String imageCopyrightLink = imgObject.getString("copyrightlink");

//            String imageText = "";
//            imageText += "<div class='g-thumb'><img src = '" + imageUrl + "'/>" + "</div>";
//            imageText += "<p><a href = '" + imageCopyrightLink + "'></p>";
//            imageText += "版权：" + imageCopyright + "</a></p>";
            resultMap.put("imageUrl", imageUrl);
        }
        JSONObject calendarResultObject = RequestUtil.postForObject(RequestUtil.PERPETUAL_CALENDAR_URL, null);
        // 正文
        String mainBody = "";
        if (calendarResultObject != null && "200".equals(calendarResultObject.getString("code"))) {
            String calendarContent = "";
            JSONObject dataObject = calendarResultObject.getJSONObject("data");
            JSONObject solarObject = dataObject.getJSONObject("solar");
            JSONObject lunarObject = dataObject.getJSONObject("lunar");

            calendarContent += "<p>" + solarObject.getString("year") + "年" + solarObject.getString("month") + "月" + solarObject.getString("date") + "日，";
            calendarContent += "农历" + lunarObject.getString("year") + "[" + lunarObject.getString("animal") + "]年" + lunarObject.getString("month") + "" + lunarObject.getString("date") + "，" + solarObject.getString("day") + "，上午好。";
            mainBody += calendarContent + "</p>";
        }
        JSONObject textJsonObject = RequestUtil.postForObject(RequestUtil.NEW_TEXT_URL, null);
        if (textJsonObject != null && "200".equals(textJsonObject.getString("code"))) {
            JSONObject dataJsonObject = textJsonObject.getJSONObject("data");
            // 主题
            String tag = dataJsonObject.getString("tag");
            // 来自
            String origin = dataJsonObject.getString("origin");
            String content = dataJsonObject.getString("content");

            mainBody += "<p>" + content + "</p><p>出自：" + origin + "</p>";
        }
        resultMap.put("mainBody", mainBody);
        // 微博热搜
        HttpHeaders headers = new HttpHeaders();
        headers.add("access-key", CODER_ACCESS_KEY);
        headers.add("secret-key", CODER_SECRET_KEY);
        JSONObject weiboResultObject = RequestUtil.getForObject(RequestUtil.WEIBO_URL + "?size=15", headers);
        if("200".equals(weiboResultObject.getString("code"))){
            JSONArray dataJsonArray = weiboResultObject.getJSONArray("data");
            StringBuilder weiboContent = new StringBuilder();
            for (int i = 0; i < dataJsonArray.size(); i++) {
                JSONObject itemObject = dataJsonArray.getJSONObject(i);
                weiboContent.append("<a style=\"margin: 4px 0;\" href=\"").append(itemObject.getString("url")).append("')\">").append(itemObject.getString("rank")).append("、").append(itemObject.getString("keyword")).append("</a><br/>");
            }
            resultMap.put("weiboContent", weiboContent.toString());
        }
        // 知乎热搜
        JSONObject zhihuResultObject = RequestUtil.getForObject(RequestUtil.ZHIHU_URL, headers);
        if("200".equals(zhihuResultObject.getString("code"))){
            JSONArray dataJsonArray = zhihuResultObject.getJSONArray("data");
            StringBuilder zhihuContent = new StringBuilder();
            for (int i = 0; i < dataJsonArray.size(); i++) {
                JSONObject itemObject = dataJsonArray.getJSONObject(i);
                zhihuContent.append("<a style=\"margin: 4px 0;\" href=\"").append(itemObject.getString("url")).append("\">").append(itemObject.getString("rank")).append("、").append(itemObject.getString("keyword")).append("</a><br/>");
            }
            resultMap.put("zhihuContent", zhihuContent.toString());
        }
        // 今日歌曲
        JSONObject musicResultObject = RequestUtil.getForObject(RequestUtil.MUSIC_RECOMMEND_URL, headers);
        if("200".equals(musicResultObject.getString("code"))){
            JSONObject dataJsonObject = musicResultObject.getJSONObject("data");
            JSONArray songsJsonArray = dataJsonObject.getJSONArray("songs");
            if(songsJsonArray.size() > 0){
                JSONObject musicObject = songsJsonArray.getJSONObject(0);
                String songUrl = musicObject.getString("songUrl");
//                String musicId = "";
//                if(StringUtils.isNotBlank(songUrl)){
//                    musicId = songUrl.substring(songUrl.indexOf("?id=") + 4, songUrl.indexOf(".mp3"));
//                }
                resultMap.put("musicId", songUrl);
                resultMap.put("musicTitle", musicObject.getString("title"));
                resultMap.put("musicSinger", musicObject.getString("singer"));
            }
        }
        // 历史的今天
        JSONObject todayResultObject = RequestUtil.getForObject(RequestUtil.RESOU_TODAY_URL, headers);
        if("200".equals(todayResultObject.getString("code"))){
            JSONArray dataJsonArray = todayResultObject.getJSONArray("data");
            StringBuilder todayContent = new StringBuilder();
            for (int i = 0; i < dataJsonArray.size(); i++) {
                JSONObject todayObject = dataJsonArray.getJSONObject(i);
                todayContent.append("<a style=\"margin: 4px 0;\" href=\"").append(todayObject.getString("url")).append("\">").append(todayObject.getString("keyword")).append("</a><br/>");
            }
            resultMap.put("todayContent", todayContent.toString());
        }
        // 百度热搜
        JSONObject baiduResultObject = RequestUtil.getForObject(RequestUtil.BAIDU_URL, headers);
        if("200".equals(baiduResultObject.getString("code"))){
            JSONArray dataJsonArray = baiduResultObject.getJSONArray("data");
            StringBuilder baiduContent = new StringBuilder();
            for (int i = 0; i < dataJsonArray.size(); i++) {
                JSONObject baiduObject = dataJsonArray.getJSONObject(i);
                baiduContent.append("<a style=\"margin: 4px 0;\" href=\"").append(baiduObject.getString("url")).append("\">").append(baiduObject.getString("rank") + "、" + baiduObject.getString("keyword")).append("</a><br/>");
            }
            resultMap.put("baiduContent", baiduContent.toString());
        }
        return resultMap;
    }

    /**
     * 根据模板发送邮件
     *
     * @return result
     * @author yh
     * @date 2022/6/4
     */
    @Scheduled(cron = "0 0 8 * * *")
    public void sendHtmlMail() {
        // 获取发送的用户
        List<EmailUser> emailUsers = emailUserService.queryList();
        if (CollectionUtils.isEmpty(emailUsers)) {
            log.info("没有要发送的用户");
        }
        Map<String, String> emailContent = getContent();

        for (EmailUser user : emailUsers) {
            if (StringUtils.isBlank(user.getEmail())) {
                continue;
            }
            emailContent.put("userName", user.getNickName());
            emailContent.put("endingText", user.getEndingText());
//            // 邮件内容
            String content = FtlUtil.buildContent(emailContent);
//            String content = "";
            // 添加发送记录
            Long recordId = emailRecordService.saveEmailRecord(content, user.getUserId());
            // 获取发送次数
            Long sendCount = emailRecordService.getSendCount(user.getUserId());
            try {
                String[] emailList = {user.getEmail()};
                sendHtmlMail(subject + "(第" + (sendCount + 1) + "期)", content, emailList);
                // 更新发送状态
                emailRecordService.updateState(recordId);
            } catch (MessagingException e) {
                log.error("发送失败，recordId：" + recordId + "。"+ e.getMessage());
            }
        }
    }

    /**
     * 发送文本邮件
     *
     * @param subject 主题
     * @param content 内容
     * @param toWho   发给谁
     * @author yh
     * @date 2022/6/4
     */
    public void sendHtmlMail(String subject, String content, String[] toWho) throws MessagingException {
        //检验参数：邮件主题、收件人、邮件内容必须不为空才能够保证基本的逻辑执行
        if (subject == null || toWho == null || toWho.length == 0 || content == null) {
            log.error("邮件-> {} 无法继续执行，因为缺少基本的参数：邮件主题、收件人、邮件内容", subject);
            throw new RuntimeException("模板邮件无法继续发送，因为缺少必要的参数！");
        }
        //html
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        //try {
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, DEFAULT_ENCODING);
        //设置邮件的基本信息
        handleBasicInfo(helper, subject, content, toWho);
        //发送邮件
//        try {
        mailSender.send(mimeMessage);
        log.info("html邮件发送成功");
//        } catch (MessagingException e) {
//            log.error("发送邮件出错->{}", subject);
//        }
        log.info("发送邮件成功: 主题->{}", subject, toWho);
    }

    public void handleBasicInfo(MimeMessageHelper mimeMessageHelper, String subject, String content, String[] toWho) {
        try {
            //设置发件人
            mimeMessageHelper.setFrom(nickname + '<' + userName + '>');
            //设置邮件的主题
            mimeMessageHelper.setSubject(subject);
            //设置邮件的内容
            mimeMessageHelper.setText(content, true);
            //设置邮件的收件人
            mimeMessageHelper.setTo(toWho);
        } catch (MessagingException e) {
            log.error("html邮件基本信息出错->{}", subject);
        }
    }
}
